package com.panshi.controller;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.panshi.bean.Dynamic;
import com.panshi.bean.PageBean;
import com.panshi.config.JWTUtils;
import com.panshi.service.AppUserService;
import com.panshi.entity.AppUser;
import com.panshi.service.FeignAppUserClient;
import feign.Param;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@Api(tags = "app用户业务接口")
@Slf4j
public class AppUserController implements FeignAppUserClient {

    @Autowired
    private AppUserService appUserService;

    @ApiOperation("根据userId查询用户信息")
    @GetMapping("app-user/info/{userId}")
    @ApiImplicitParam(name = "userId", value = "用户id", required = true)
    public AppUser queryUserInfo(@PathVariable Integer userId){

        return appUserService.queryUserInfo(userId);

    }

    @GetMapping("app-user/queryEssay")
    public List<Dynamic> queryUserEssayById (@Param(value = "id") String id, String pageNumber,String pageSize){


        log.info("查询用户的动态信息！用户id：{}" , id);
        log.info("查询用户的动态信息！pageNumber：{}" ,pageNumber );
        log.info("查询用户的动态信息！pageSize：{}" ,pageSize );

        PageBean page = new PageBean();
        page.setId(id);
        page.setPageSize(Integer.valueOf(pageSize));
        page.setPageNumber(Integer.valueOf(pageNumber));


        return appUserService.queryUserDynamic(page);
    }


    @GetMapping("app-user/initUserInfo")
    public Map<String ,Object> initUserInfo(HttpServletRequest request){
        // 从请求头中获取token
        String token = request.getHeader("Authorization");

        log.info("token:[{}]",token);

        Map<String ,Object> map = new HashMap();

        if (!StringUtils.isNoneBlank(token)) {
            map.put("static",false);
            map.put("msg","token已失效");

            return map;
        }

        DecodedJWT decodedJWT = JWTUtils.getTokenInfo(token);
        String userId = decodedJWT.getClaim("id").asString();

        log.info("userId:[{}]",userId);
        map.put("static",true);
        map.put("msg","查询成功");
        map.put("userInfo",this.queryUserInfo(Integer.valueOf(userId) )) ;

        return map;
    }



}
